package com.demo.personalaccountingbackend.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.demo.personalaccountingbackend.entity.Category;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 类描述信息
 *
 * @author zgx
 * @version 1.0
 * @date 2025/10/15 11:42
 */
@Mapper
public interface CategoryMapper extends BaseMapper<Category> {

    /**
     * 根据类型查询分类
     */
    @Select("SELECT * FROM category WHERE type = #{type} and status  = 0 ORDER BY sort ASC, id ASC")
    List<Category> findByType(@Param("type") Integer type);

    /**
     * 检查分类名称是否存在（同一类型下）
     */
    @Select("SELECT COUNT(1) > 0 FROM category WHERE name = #{name} AND type = #{type}")
    boolean existsByNameAndType(@Param("name") String name, @Param("type") Integer type);

    /**
     * 检查分类是否被记账记录使用
     */
    @Select("SELECT COUNT(1) > 0 FROM account_record WHERE category_id = #{categoryId}")
    boolean existsRecordByCategoryId(@Param("categoryId") Long categoryId);

    /**
     * 查询所有分类（包含层级关系）
     */
    @Select("SELECT * FROM category where status  = 0 ORDER BY type, sort, id ")
    List<Category> selectAllWithTree();

    /**
     * 根据父级ID查询子分类
     */
    @Select("SELECT * FROM category WHERE parent_id = #{parentId} ORDER BY sort, id")
    List<Category> selectByParentId(Long parentId);

    /**
     * 根据类型查询分类
     */
    @Select("SELECT * FROM category WHERE type = #{type} and status  = 0 ORDER BY sort, id ")
    List<Category> selectByType(Integer type);
}